#include "client.h"
#include "chat.h"
#include "UI/ui_myFunc.h"

#include "config.h"

using namespace std;
using namespace Chat;

User loginUser{
    .userName     = {},
    .password     = {},
    .userAddr     = {},
    .sockfd       = -1,
    .speak        = Flag::YES,
    .registerTime = {},
};

vector<pair<string, lv_obj_t* [2]>> ChatterList{};

vector<pair<lv_obj_t*, vector<lv_obj_t*>>> chatMsgContList{};

pair<string, lv_obj_t* [2]> curChatTo{};

StateRet ClientRegisterUser(int sockfd, const User& userInfo)
{
    /*声明用户需要的注册信息*/
    User    user{userInfo};
    char    buf[MAX_LINE]{};
    Message message{};

    // 当前用户允许发言
    user.speak = Flag::YES;

    memset(buf, 0, MAX_LINE);
    memcpy(buf, &user, sizeof(user));
    send(sockfd, buf, sizeof(buf), 0);

    /*接收注册结果*/
    memset(buf, 0, MAX_LINE);
    recv(sockfd, buf, sizeof(buf), 0);
    message = Message{};
    memcpy(&message, buf, sizeof(buf));

    Container5_add_obj(message);

    printf("%s\n", message.content);
    return message.msgRet;
}

StateRet ClientLoginUser(int sockfd, const User& userInfo)
{
    int ret;
    /*声明用户登陆信息*/
    User    user{userInfo};
    char    buf[MAX_LINE];
    Message message;

    /*发送用户登陆信息到服务器*/
    memset(buf, 0, MAX_LINE);
    memcpy(buf, &user, sizeof(user));
    send(sockfd, buf, sizeof(buf), 0);

    /*接收登陆结果*/
    memset(buf, 0, MAX_LINE);
    recv(sockfd, buf, sizeof(buf), 0);
    memset(&message, 0, sizeof(message));
    memcpy(&message, buf, sizeof(buf));

    printf("%s\n", message.content);

    /*如果登陆成功，则进入聊天界面*/
    if (message.msgRet == StateRet::SUCCESS) {

        pthread_t pid; /*处理接收消息线程*/

                       /*创建接收消息线程*/
        ret = pthread_create(&pid, NULL, ClientRecvMsg, (void*)&sockfd);
        if (ret != 0) {
            printf("软件异常，请重新登录！\n");
            message = Message{};
            strcpy(message.sendName, user.userName);
            message.msgType = MessageType::EXIT;
            send(sockfd, buf, sizeof(buf), 0);
            close(sockfd);
            exit(1);
        }
    }   // if

    Container5_add_obj(message);
    return message.msgRet;
}
